# by kevincat, scanning the rssi value from nearby aps.

import wx
import commands
import re
import urllib, urllib2
#from sample import *

class ScanFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "RSSI Scanning Console", style = wx.DEFAULT_FRAME_STYLE)
        
        self.submit = wx.Button(self, -1, "Press to Scan")
        self.send = wx.Button(self, -1, "Send Results")
        self.autosend = wx.Button(self, -1, "Auto Send")
        self.outputLabel = wx.StaticText(self, -1, " The Scanned Result:")
        self.output = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
        self.inputUrlLabel = wx.StaticText(self, -1, " Input the url to send RSSI:")
        self.inputUrl = wx.TextCtrl(self, -1,  size=(250, -1))
        self.scan = Scan()
        self.timer = wx.Timer(self)
        #self.timer.Start(100)
        
        self.__make_menu()
        self.__do_layout()
        self.__attach_event()  
	
    def __make_menu(self):
		#-- File Menu 
        FileMenu = wx.Menu()
        Open = FileMenu.Append(-1, "&Open\tCtrl-O")
        FileMenu.AppendSeparator()
        exit = FileMenu.Append(-1, "E&xit\tCtrl-Q")
        #self.Bind(wx.EVT_MENU, self.OnExit, exit)
        
        #-- Edit Menu
        EditMenu = wx.Menu()
        Undo = EditMenu.Append(-1, "&Undo\tCtrl-Z")
        EditMenu.AppendSeparator()
        Cut = EditMenu.Append(-1, "Cu&t\tCtrl-X")
        Copy = EditMenu.Append(-1, "&Copy\tCtrl-C")
        Paste = EditMenu.Append(-1, "&Paste\tCtrl-V")
        
        #-- Help Menu
        HelpMenu = wx.Menu()
        About = HelpMenu.Append(-1, "&About")
        HelpMenu.AppendSeparator()
        GPCHelp = HelpMenu.Append(-1, "&GPC Help\tF1")
        
        ## Append menu in MenuBar
        menuBar = wx.MenuBar()
        menuBar.Append(FileMenu, "&File")
        menuBar.Append(EditMenu, "&Edit")
        menuBar.Append(HelpMenu, "&Help")
        
        self.SetMenuBar(menuBar)        
        
    def __do_layout(self):
        self.SetMaxSize((700, 800))		
        self.output.SetMinSize((300, 400))
        
        sizer_v_output = wx.BoxSizer(wx.VERTICAL)
        sizer_v_output.Add(self.outputLabel, 0, wx.ALL, 5)
        sizer_v_output.Add(self.output, 0, wx.ALL, 5)
        sizer_v_output.Add(self.inputUrlLabel, 0, wx.ALL)
        sizer_v_output.Add(self.inputUrl, 0, wx.ALL, 5)
        sizer_h_submit = wx.BoxSizer(wx.HORIZONTAL)
        sizer_h_submit.Add(self.submit, 0, wx.ALL, 5)
        sizer_h_submit.Add(self.send, 0, wx.ALL, 5)
        sizer_h_submit.Add(self.autosend, 0, wx.ALL, 5)
        sizer_v_output.Add(sizer_h_submit, wx.ALL, 5)
        
        sizer_h = wx.BoxSizer(wx.HORIZONTAL)
        sizer_h.Add(sizer_v_output, 0, wx.ALL, 5)
        
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_v.Add(sizer_h, 0, wx.ALL | wx.EXPAND, 0)
		
        self.SetAutoLayout(1)
        self.SetSizer(sizer_v)
        sizer_v.Fit(self)
        sizer_v.SetSizeHints(self)
        self.Layout()
		
    def __attach_event(self):
        self.submit.Bind(wx.EVT_BUTTON, self.OnSubmit)
        self.send.Bind(wx.EVT_BUTTON, self.OnSend)
        self.autosend.Bind(wx.EVT_BUTTON, self.OnAutoSend)
        self.Bind(wx.EVT_TIMER, self.TimerHandler)
        #self.showGraph.Bind(wx.EVT_BUTTON, self.OnShowGraph)
   
    def OnSubmit(self, event):
        print 'press scan, the scan start!'
        self.scan.Run()
        s = self.scan.MacRssiPair
        o = ''
        for _s in s:
            o += 'the AP\'s mac address is:\r\n' 
            o += _s
            o += '\nthe scanned RSSI is:' + str(s[_s]) 
            o += '\n'
            self.output.SetValue(o)
        self.scan.SendUrl = self.inputUrl.GetValue()
        
    def OnSend(self, event):
        self.scan.Send()
        
    def OnAutoSend(self, evnet):
        #self.TimerHandler()
        #self.timer.Start(3000)
        self.timer.Start(50)
        
    def TimerHandler(self, event):
        self.scan.Send()
        print 'send the mac-rssi pair successfully'
        
class Scan():
    def __init__(self):
        self.ScanResult = ''
        self.MacRssiPair = {}
        self.SendUrl = ''
    
    def Run(self):
        #get output from iwlist scanning
        ot = commands.getstatusoutput('iwlist wlan0 scanning')
        #get the second part of the tuple
       	ot = ot[1]
        self.ScanResult = ot
        #self.ScanResult = sample_input
        
        ''' regex code '''
        # match each address and Signal level
        r1 = re.compile(r'Address.+\d{2}')
        r2 = re.compile(r'Signal.+\d{2}')

        _r1 = r1.findall(self.ScanResult)
        _r2 = r2.findall(self.ScanResult)
        
        _l = len(_r1)
	self.MacRssiPair = {}        
	while _l > 0:
            _l = _l - 1
            self.MacRssiPair[_r1[_l][9:]] = int(_r2[_l][14:])
        
        print self.MacRssiPair
      
    def Send(self):
        url = self.SendUrl 
        print 'Send to the url:' + url
        if url == 'localhost' or url == 'local':
            url = 'http://localhost:8080/t1/postrssi/'
        elif url == 'lab' or url == 'kevincat':
            url = 'http://lab.kevincat.info/t1/postrssi/'
        values = { 'rssi' : self.MacRssiPair } 
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        print response.read()
    
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = ScanFrame()
    frame.Show()
    app.MainLoop()
